package com.test.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

//分库精确查找策略
public class MyPreciseDSShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * select * from course where cid = ? or cid in (?,?)
     *
     * @param availableTargetNames 真实数据源集合[m1,m2]
     * @param shardingValue        逻辑表，主键，主键值
     * @return 数据源m1或者m2
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        //逻辑表
        String logicTableName = shardingValue.getLogicTableName();
        //主键
        String columnName = shardingValue.getColumnName();
        //主键值
        Long columnValue = shardingValue.getValue();

        //如下实现找出库
        BigInteger columnValueBigInteger = BigInteger.valueOf(columnValue);
        BigInteger tableSuffix = (columnValueBigInteger.mod(new BigInteger("2"))).add(new BigInteger("1"));
        String availableTargetName = "m" + tableSuffix;
        if (availableTargetNames.contains(availableTargetName)) {
            return availableTargetName;
        }
        throw new UnsupportedOperationException("route " + availableTargetName + " is not supported ,please check your config");
    }
}
